package com.atguigu.day06;

import com.atguigu.utils.ItemViewCountPerWindow;
import com.atguigu.utils.UserBehavior;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.SlidingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Comparator;

// 实时热门商品
// 每隔5分钟计算一次过去一小时的pv最多的3个商品
public class Example6 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<UserBehavior> stream = env
                .readTextFile("/home/zuoyuan/flinktutorial0722/src/main/resources/UserBehavior.csv")
                .map(new MapFunction<String, UserBehavior>() {
                    @Override
                    public UserBehavior map(String value) throws Exception {
                        String[] arr = value.split(",");
                        return new UserBehavior(
                                arr[0], arr[1], arr[2], arr[3],
                                Long.parseLong(arr[4]) * 1000L
                        );
                    }
                })
                .filter(r -> r.type.equals("pv"))
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<UserBehavior>forMonotonousTimestamps()
                                .withTimestampAssigner(new SerializableTimestampAssigner<UserBehavior>() {
                                    @Override
                                    public long extractTimestamp(UserBehavior element, long recordTimestamp) {
                                        return element.ts;
                                    }
                                })
                );

        // 先求每个商品在每个窗口中的pv次数
        SingleOutputStreamOperator<ItemViewCountPerWindow> itemViewCountPerWindowResults = stream
                .keyBy(r -> r.itemId)
                .window(SlidingEventTimeWindows.of(Time.hours(1), Time.minutes(5)))
                .aggregate(new CountAgg(), new WindowResult());

        itemViewCountPerWindowResults
                .keyBy(r -> r.windowEndTime)
                .process(new TopN(3))
                .print();

        env.execute();
    }

    public static class CountAgg implements AggregateFunction<UserBehavior, Long, Long> {
        @Override
        public Long createAccumulator() {
            return 0L;
        }

        @Override
        public Long add(UserBehavior value, Long accumulator) {
            return accumulator + 1L;
        }

        @Override
        public Long getResult(Long accumulator) {
            return accumulator;
        }

        @Override
        public Long merge(Long a, Long b) {
            return null;
        }
    }

    public static class WindowResult extends ProcessWindowFunction<Long, ItemViewCountPerWindow, String, TimeWindow> {
        @Override
        public void process(String s, Context context, Iterable<Long> elements, Collector<ItemViewCountPerWindow> out) throws Exception {
            out.collect(new ItemViewCountPerWindow(
                    s,
                    elements.iterator().next(),
                    context.window().getStart(),
                    context.window().getEnd()
            ));
        }
    }

    public static class TopN extends KeyedProcessFunction<Long, ItemViewCountPerWindow, String> {
        private int n;

        public TopN(int n) {
            this.n = n;
        }

        private ListState<ItemViewCountPerWindow> listState;

        @Override
        public void open(Configuration parameters) throws Exception {
            listState = getRuntimeContext().getListState(
                    new ListStateDescriptor<ItemViewCountPerWindow>("list-state", Types.POJO(ItemViewCountPerWindow.class))
            );
        }

        @Override
        public void processElement(ItemViewCountPerWindow value, Context ctx, Collector<String> out) throws Exception {
            listState.add(value);

            // 当大于等于value.windowEndTime + 100L的水位线到达KeyedProcessFunction以后
            // value.windowEndTime所标识的窗口中的所有统计信息都已到达
            ctx.timerService().registerEventTimeTimer(value.windowEndTime + 100L);
        }

        @Override
        public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
            // 将数据从listState中取出，并放入ArrayList
            ArrayList<ItemViewCountPerWindow> arrayList = new ArrayList<>();
            for (ItemViewCountPerWindow e : listState.get()) arrayList.add(e);
            // 将ListState清空，节省内存
            listState.clear();

            // 排序
            arrayList.sort(new Comparator<ItemViewCountPerWindow>() {
                @Override
                public int compare(ItemViewCountPerWindow t1, ItemViewCountPerWindow t2) {
                    return t2.count.intValue() - t1.count.intValue();
                }
            });

            // 输出统计结果
            StringBuilder result = new StringBuilder();
            result
                    .append("==============================================\n")
                    .append("窗口结束时间：" + new Timestamp(timestamp - 100L))
                    .append("\n");
            for (int i = 0; i < n; i++) {
                ItemViewCountPerWindow tmp = arrayList.get(i);
                result
                        .append("第" + (i + 1) + "名的商品ID是：" + tmp.itemId + "，浏览次数是：" + tmp.count + "\n");
            }
            result
                    .append("==============================================\n");
            out.collect(result.toString());
        }
    }
}
